package net.airtheva.uniqueTask5;

import java.util.ArrayList;
import java.util.HashMap;

import net.airtheva.weather.Location;
import net.airtheva.weather.Weather;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class WidgetConfigureActivity extends Activity {

	public static final String KEY_WEATHER_ICON = "weatherIcon";
	public static final String KEY_LOCAITON_NAME = "locationName";
	public static final String KEY_WEATHER = "weather";
	public static final String KEY_TEMPERATURE = "temperature";

	ServiceConnection mServiceConnection;
	WeatherService mWeatherService;

	int mAppWidgetID = AppWidgetManager.INVALID_APPWIDGET_ID;

	ArrayList<HashMap<String, Object>> mLocationsData;

	ListView mWeathers;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_widget_configure);

		mServiceConnection = new ServiceConnection() {

			@Override
			public void onServiceConnected(ComponentName name, IBinder service) {

				mWeatherService = ((WeatherService._Binder) service).GetServive();

				updateLocationsData();
				setWeathersData(mLocationsData);

			}

			@Override
			public void onServiceDisconnected(ComponentName name) {

			}

		};
		
		mLocationsData = new ArrayList<HashMap<String, Object>>();

		mWeathers = (ListView) findViewById(R.id.activity_widget_configure_weathers);
		mWeathers.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

				boolean result = configureWidget(mAppWidgetID, position);
				
				Intent resultValue = new Intent();
				resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetID);
				if(result) {
					setResult(RESULT_OK, resultValue);
				}
				else {
					setResult(RESULT_CANCELED, resultValue);
				}
				
				Intent intent = new Intent(WeatherService.BROADCAST_ACTION_APPWIDGET_REQUEST);
				intent.putExtra(WeatherWidget.KEY_APP_WIDGET_ID, mAppWidgetID);
				
				sendBroadcast(intent);
				
				finish();
			}
		});

		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		if (extras != null) {
			mAppWidgetID = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
			setTitle("Setting up for AppWidget " + mAppWidgetID + ".");
		}

		bindService(new Intent(this, WeatherService.class), mServiceConnection, BIND_AUTO_CREATE);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.widget_configure, menu);
		return true;
	}

	@Override
	protected void onDestroy() {
		
		unbindService(mServiceConnection);
		
		super.onDestroy();
	}

	void updateLocationsData() {

		mLocationsData.clear();

		int size = mWeatherService.Locations.size();
		for (int i = 0; i < size; i++) {

			Location location = mWeatherService.Locations.get(i);

			HashMap<String, Object> map = new HashMap<String, Object>();
			if (location.Weathers[0] != null) {
				Weather currentWeather = location.Weathers[0];
				map.put(KEY_WEATHER_ICON, currentWeather.WeatherIconURI);
				map.put(KEY_LOCAITON_NAME, location.Name);
				map.put(KEY_WEATHER, currentWeather.Weather);
				map.put(KEY_TEMPERATURE, currentWeather.TemperatureCelsius);
			} else {
				map.put(KEY_WEATHER_ICON, R.drawable.ic_launcher);
				map.put(KEY_LOCAITON_NAME, location.Name);
				map.put(KEY_WEATHER, "-");
				map.put(KEY_TEMPERATURE, "-");
			}
			mLocationsData.add(map);

		}

	}

	void setWeathersData(ArrayList<HashMap<String, Object>> locationsData) {

		String[] from = new String[] { KEY_WEATHER_ICON, KEY_LOCAITON_NAME, KEY_WEATHER, KEY_TEMPERATURE };

		int[] to = new int[] { R.id.widget_weather_weatherIcon, R.id.widget_weather_locationName, R.id.widget_weather_weather, R.id.widget_weather_temperature };

		SimpleAdapter simpleAdapter = new SimpleAdapter(this, locationsData, R.layout.widget_weather, from, to);

		mWeathers.setAdapter(simpleAdapter);

	}

	boolean configureWidget(int appWidgetID, int position) {
		try {
			SharedPreferences sharedPreferences = getSharedPreferences(WeatherService.NAME_SHARED_PREFERENCES, MODE_PRIVATE);

			JSONObject j = new JSONObject(sharedPreferences.getString(WeatherService.KEY_APP_WIDGET_CONFIGURATIONS, "{}"));
			j.put(mAppWidgetID + "", position);

			sharedPreferences.edit().putString(WeatherService.KEY_APP_WIDGET_CONFIGURATIONS, j.toString()).apply();
			
			return true;
		} catch (JSONException e) {
			e.printStackTrace();
			return false;
		}
	}

}
